package online.inote.naruto.api.access.admin.modules.login.controller;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import online.inote.naruto.api.access.admin.common.props.ApiAdminProperties;
import online.inote.naruto.api.access.admin.modules.base.controller.BaseController;
import online.inote.naruto.api.access.admin.modules.login.entity.UserEntity;
import online.inote.naruto.api.access.jwt.JwtHelper;
import online.inote.naruto.cache.CacheSupport;
import online.inote.naruto.common.utils.response.ExtendResponse;
import online.inote.naruto.common.utils.response.Response;
import online.inote.naruto.utils.DateTimeUtils;
import online.inote.naruto.utils.StringUtils;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * @description 系统管理用户Controller
 * @author XQF.Sui
 * @date 2021/08/03 10:45
 */
@RestController
@RequestMapping(value = "user")
public class UserController extends BaseController {

  private final ApiAdminProperties props;

  public UserController(ApiAdminProperties props) {
    this.props = props;
  }

  /**
   * 登录
   *
   * @param user 用户信息
   * @return
   */
  @PostMapping(value = "login")
  public Response<String> login(@RequestBody UserEntity user) {

    if (StringUtils.isBlank(user.getUsername()) || StringUtils.isBlank(user.getPassword())) {
      return ExtendResponse.fail("用户名密码不能为空");
    }

    String password = user.getPassword();
    ApiAdminProperties.Administrator administrator = props.getAdministrator();

    if (!StringUtils.equals(user.getUsername(), administrator.getUsername())
        || !StringUtils.equals(password, administrator.getPassword())) {
      return ExtendResponse.fail("账号或密码错误");
    }

    // 生成唯一安全码
    user.setSecurityKey(UUID.randomUUID().toString());
    user.setPassword(null);

    String token =
        JwtHelper.genToken(
            user.getId(),
            user.getUsername(),
            JSON.parseObject(JSON.toJSONString(user)),
            DateTimeUtils.getNow());

    CacheSupport.cache(props.getCache().getCacheKeyPrefix() + user.getId(), token, 1800);

    return ExtendResponse.success(token);
  }

  /**
   * 用户信息
   *
   * @param token
   * @return
   */
  @GetMapping(value = "info")
  public Response<UserEntity> info(@Param(value = "token") String token) {
    Jws<Claims> claims = JwtHelper.getClaims(token);

    return ExtendResponse.success(
        UserEntity.builder()
            .username((String) claims.getBody().get(UserEntity.Fields.username))
            .build());
  }

  @PostMapping(value = "logout")
  public Response<Object> logout(@RequestHeader(value = "naruto-token") String token) {
    String cacheTokenId = JwtHelper.getClaims(token).getBody().getId();

    CacheSupport.delete(props.getCache().getCacheKeyPrefix() + cacheTokenId);

    return ExtendResponse.success();
  }
}
